package com.lq.javaweb;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerTest {
    public static void main(String[] args) throws Exception {
        // 启动一个服务器,监听本地8080端口
        ServerSocket serverSocket = new ServerSocket(8080);

        //写一个死循环，一直等着这个端口
        while (true) {
            Socket accept = serverSocket.accept();

            // 获得输入流
            InputStream inputStream = accept.getInputStream();
            byte[] buf = new byte[1024];
            int len;
            while (inputStream.available() > 0) {//如果端口还有输入就打印出来，没有就退出
                len = inputStream.read(buf);
                System.out.print(new String(buf,0,len));
            }

            //输出流
            OutputStream outputStream = accept.getOutputStream();
            // 按照http协议的格式封装一个报文
            String response = "HTTP/1.1 200 OK\r\n" +
                    "Content-Length: 39\r\n" +
                    "Content-Type: text/html;charset=UTF-8\r\n\r\n" +
                    "<h1 style=\"color:red\">hello server!<h1>";
            // 将报文写出给浏览器
            outputStream.write(response.getBytes());
            outputStream.flush();
            // 这个输出流不要着急关，因为突然的关闭会导致浏览器和服务器的连接断开


            inputStream.close();
            outputStream.close();
            accept.close();
        }

    }
}
